from django.db import models, connection
from django.http import JsonResponse


# Create your models here.
# class Rc_admin(models.Model):
#     print("======================================================================")
#     admin_username = models.CharField(max_length=100)
#     admin_password = models.CharField(max_length=100)
#
#     def __str__(self):
#         return self.admin_username
#
#     def authenticate(self, username, password):
#         """
#         验证用户登录信息是否匹配
#         """
#         return self.admin_username == username and self.admin_password == password
#
#     def fetch_users_by_name(name):
#         print(name)
#         # 查询指定名字的人员数据
#         users_data = Rc_admin.objects.filter(admin_username =name)
#
#         return users_data
# from django.db import models

class Users(models.Model):
    table_name="emp"
    def fetch_users_by_name(self,name):
        with connection.cursor() as cursor:
            # 构建 SQL 查询语句
            sql_query = f"SELECT * FROM {self.table_name} WHERE username = %s"
            # 执行 SQL 查询
            cursor.execute(sql_query, [name])
            # 获取查询结果
            users_data = cursor.fetchall()
            print(users_data)
        return users_data
    def fetch_exist(self,name,password):
        with connection.cursor() as cursor:
            # 构建 SQL 查询语句
            sql_query = f"SELECT * FROM {self.table_name} WHERE username = %s AND password = %s"
            print(sql_query)
            # 执行 SQL 查询
            cursor.execute(sql_query, [name,password])
            # 获取查询结果
            users_data = cursor.fetchall()
            print(users_data)
        return users_data

class Response(models.Model):
    def response(request,responsevalue):
        responseData=""
        if responsevalue==1:
            responseData = {'success': True, 'message': 'Login successful','ec':0}
            response = JsonResponse(responseData)
        else:
            responseData =({'default': False, 'message': 'Invalid credentials','ec':1})
            response = JsonResponse(responseData,status=400)
        # 创建 JSON 响应，并设置自定义的响应头
        response['Access-Control-Allow-Origin'] = 'http://localhost:8080'
        return response
